package com.nifostasky.comic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nifostasky.comic.common.threadlocal.SessionLoad;
import com.nifostasky.comic.entitys.CoCollectInfo;
import com.nifostasky.comic.entitys.CoDetailedInfo;
import com.nifostasky.comic.entitys.CoSpiderInfo;
import com.nifostasky.comic.exceptions.BusinessException;
import com.nifostasky.comic.mapper.CoCollectInfoMapper;
import com.nifostasky.comic.service.CoCollectInfoService;
import com.nifostasky.comic.service.CoDetailedInfoService;
import com.nifostasky.comic.service.CoSpiderInfoService;
import com.nifostasky.comic.vos.CoSpiderDetailedInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户收藏漫画信息表(CoCollectInfo)表服务实现类
 *
 * @author makejava
 * @since 2022-02-14 21:09:02
 */
@Service("coCollectInfoService")
public class CoCollectInfoServiceImpl extends ServiceImpl<CoCollectInfoMapper, CoCollectInfo> implements CoCollectInfoService {
    @Autowired
    private CoDetailedInfoService coDetailedInfoService;
    @Autowired
    private CoSpiderInfoService coSpiderInfoService;

    @Override
    public Map<String, Object> coCollectInfoPageByUser(Integer pageIndex, Integer pageSize, Long userId) {
        Map<String,Object> map = new HashMap<>();
        List<CoSpiderDetailedInfoVO> results =  new ArrayList<>();
        if (Objects.isNull(pageIndex)) pageIndex = 1;
        if (Objects.isNull(pageSize)) pageSize = 10;
        if (Objects.isNull(userId)) new BusinessException("用户id不能为空",-500);
        Page<CoCollectInfo> page = this.page(new Page<CoCollectInfo>(pageIndex, pageSize), new QueryWrapper<CoCollectInfo>().lambda()
                .eq(CoCollectInfo::getUserId, userId)
                .orderByDesc(CoCollectInfo::getCreateTime)
        );
        if (Objects.isNull(page.getRecords())) return null;
        List<Long> detailedIds = page.getRecords().stream().map(i -> i.getDetailedId()).collect(Collectors.toList());
        for (int i = 0; i < detailedIds.size(); i++){
            CoDetailedInfo detailedInfo = coDetailedInfoService.getById(detailedIds.get(i));
            CoSpiderDetailedInfoVO result = new CoSpiderDetailedInfoVO();
            BeanUtils.copyProperties(detailedInfo,result);
            result.setSpiderId(page.getRecords().get(i).getSpiderId());
            result.setId(page.getRecords().get(i).getId());
            results.add(result);
        }
        map.put("total",page.getTotal());
        map.put("data",results);
        return map;
    }

    @Override
    public List<CoSpiderDetailedInfoVO> coCollectInfoListByUser(Long userId) {
        List<CoSpiderDetailedInfoVO> results =  new ArrayList<>();
        if (Objects.isNull(userId)) new BusinessException("用户id不能为空",-500);
        List<CoCollectInfo> list = this.list(new QueryWrapper<CoCollectInfo>().lambda()
                .eq(CoCollectInfo::getUserId, userId)
                .orderByDesc(CoCollectInfo::getCreateTime)
        );
        if (Objects.isNull(list)) return null;
        List<Long> detailedIds = list.stream().map(i -> i.getDetailedId()).collect(Collectors.toList());
        for (int i = 0; i < detailedIds.size(); i++){
            CoDetailedInfo detailedInfo = coDetailedInfoService.getById(detailedIds.get(i));
            CoSpiderDetailedInfoVO result = new CoSpiderDetailedInfoVO();
            BeanUtils.copyProperties(detailedInfo,result);
            result.setSpiderId(list.get(i).getSpiderId());
            result.setId(list.get(i).getId());
            results.add(result);
        }
        return results;
    }

    @Transactional
    @Override
    public Integer saveCollectComic(CoSpiderDetailedInfoVO info) {
        if (Objects.isNull(info) || Objects.isNull(info.getSpiderId()))
            throw new BusinessException("缺少关键信息,可能是缺少python文件id", -500);
        CoDetailedInfo coDetailedInfo = new CoDetailedInfo();
        CoCollectInfo coCollectInfo = new CoCollectInfo();
        //漫画详细信息入库
        BeanUtils.copyProperties(info,coDetailedInfo);
        coDetailedInfoService.save(coDetailedInfo);
        //建立关联 收藏
        coCollectInfo.setSpiderId(info.getSpiderId());
        coCollectInfo.setDetailedId(coDetailedInfo.getId());
        coCollectInfo.setUserId(SessionLoad.getLocalData().getUserId());
        coCollectInfo.setUserName(SessionLoad.getLocalData().getUserName());
        coCollectInfo.setCreateTime(new Date());
        this.save(coCollectInfo);
        return 1;
    }

    @Override
    public Integer cancelCollectComic(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) return 2;
        List<Long> detailedIds = this.list().stream().map(i -> i.getDetailedId()).collect(Collectors.toList());
        coDetailedInfoService.removeByIds(detailedIds);
        this.removeByIds(ids);
        return 1;
    }
}